package com.nari.ncps.screen.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Map;

public class AppInfoOutputListener implements ApplicationListener<ApplicationStartedEvent> {
    public AppInfoOutputListener() {
    }

    public void onApplicationEvent(ApplicationStartedEvent event) {
        ConfigurableApplicationContext config = event.getApplicationContext();
        Environment env = config.getEnvironment();
        String ip = null;
        Map<String, IElementConfig> elements = null;

        try {
            ip = InetAddress.getLocalHost().getHostAddress();
            elements = config.getBeansOfType(IElementConfig.class);
        } catch (UnknownHostException var13) {
            UnknownHostException e = var13;
//            LogUtil.error(e.getMessage());
            e.printStackTrace();
        }

        String name = env.getProperty("spring.application.name");
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        String version = env.getProperty("discovery.server.version");
        StringBuilder msg = new StringBuilder();
        msg.append("\n----------------------------------------------------------").append("\n\tApplication ").append(name).append(" is running!").append("\n\tVersion: \t").append(version);
        if (CollUtil.isNotEmpty(elements)) {
            msg.append("\n\n\tLoad Elements: ");
            Iterator var11 = elements.values().iterator();

            while(var11.hasNext()) {
                com.nari.ncps.screen.config.IElementConfig element =
                        (com.nari.ncps.screen.config.IElementConfig)var11.next();
                msg.append("\n\t\t").append(element.getName()).append("\t").append(StrUtil.subBefore(element.getClass().getSimpleName(), "$", false));
            }
        }

        msg.append("\n\n\tAccess URLs:").append("\n\t\tLocal: \t\thttp://localhost:").append(port).append(path).append("\n\t\tExternal: \thttp://").append(ip).append(":").append(port).append(path).append("\n----------------------------------------------------------");
        System.out.println(msg.toString());
    }
}